<!--
 * @Author: your name
 * @Date: 2021-09-21 14:09:13
 * @LastEditTime: 2022-02-21 17:29:52
 * @LastEditors: ke.xue
 * @Description: In User Settings Edit
 * @FilePath: \product-display\src\page\operate\product\list.vue
-->
<template>
  <div class="productList" style="height: calc( 100% - 80px )">
    <div class="pageTop">
      <el-row>
        <el-col :xs="xsF" :sm="smF" :md="mdF" :lg="lgF" :xl="xlF">
          <span>商品分类:</span>
          <el-cascader v-model="parentId" :options="options" clearable
          :props="{ checkStrictly: true }" :show-all-levels="false" placeholder="选择商品分类"></el-cascader>
        </el-col>
        <el-col :xs="xsb" :sm="smb" :md="mdb" :lg="lgb" :xl="xlb">
          <el-button @click="searchQuery">查询</el-button>
          <el-button @click="toAdd">新增</el-button>
        </el-col>
      </el-row>
    </div>
    <div class="tableBox" style="height: calc( 100% - 100px )">
      <el-table
        :data="tableData"
        class="typeTable"
        border>
        <el-table-column
          prop="imageName"
          label="名称"
          width="180">
        </el-table-column>
        <el-table-column
          prop="imageName"
          label="分类"
          :formatter="formatter"
          width="150">
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          width="180">
        </el-table-column>
        <el-table-column
          prop="updateTime"
          label="更新时间"
          width="180">
        </el-table-column>
        <el-table-column
          label="操作"
          width="150">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="showDetail(scope.row)">查看</el-button>
            <el-button type="text" size="small" @click="editProduct(scope.row)">编辑</el-button>
            <el-button type="text" size="small" @click="deleteProduct(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageObj.pageIndex"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageObj.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount">
      </el-pagination>
    </div>
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" width="80%">
      <div class="showDetail">
        <p>名称：{{ productDetail.imageName }}</p>
        <p>分类: {{ optionsObj[productDetail.parentId] }}</p>
        <p>商品图片：</p>
        <div class="imgLine">
          <div class="imgBox"><img :src="imgBaseUrl + productDetail.imageUrl" alt=""></div>
        </div>
        <p>商品详情图：</p>
        <div class="imgLine" v-if="productDetail.detail">
          <div class="imgBox" v-for="(detail, index) in productDetail.detail" :key="detail.id">
            <img :src="imgBaseUrl + detail.imageUrl" alt="">
            <div v-if="isEdit" class="deleteBox"><i class="el-icon-delete" @click="deleteDetail(detail, index)"></i></div>
          </div>
        </div>
        <template v-if="isEdit">
          <p>新增商品详情图</p>
          <el-upload
            ref="upload"
            action="http://47.102.146.65:8888/management-platform/batch/upload"
            list-type="picture-card"
            accept="image/*"
            multiple
            :limit="6"
            :auto-upload="false"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-change="fileChange">
            <i class="el-icon-plus"></i>
          </el-upload>
        </template>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogCancel">取 消</el-button>
        <el-button :loading="loading" type="primary" @click="dialogConfim">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import { getProductList, getProductCategoryList, deleteProduct, getProductDetail, updateProductDetail, deleteProductDetail } from '@/api/api.js'
import { listToTree } from '@/utils/util'

export default {
  name: 'ProductList',
  data () {
    return {
      dialogFormVisible: false,
      tableData: [],
      xsb: {span: 10},
      smb: {span: 8},
      mdb: {span: 6},
      lgb: {span: 4},
      xlb: {span: 3},
      xsF: {span: 14},
      smF: {span: 16},
      mdF: {span: 18},
      lgF: {span: 20},
      xlF: {span: 21},
      options: [],
      optionsObj: {},
      parentId: [],
      pageObj: {
        pageIndex: 1,
        pageSize: 10
      },
      totalCount: 0,
      imageName: '',
      productDetail: {},
      dialogTitle: '',
      uploadFile: [],
      dialogImageUrl: '',
      dialogVisible: false,
      isEdit: false,
      loading: false,
      imgBaseUrl: process.env.VUE_APP_IMAGE_URL
    }
  },
  mounted () {
    this.getOptions()
    this.getDataList()
  },
  methods: {
    deleteDetail (detail, dIndex) {
      deleteProductDetail(detail.id).then(res => {
        const arr = this.productDetail.detail
        const list = []
        arr.forEach((item, index) => {
          if (dIndex !== index) {
            list.push(item)
          }
        })
        this.productDetail.detail = list
      })
    },
    handleRemove (obj, arr) {
      this.uploadFile = arr
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    fileChange (file, arr) {
      // console.log(file, arr)
      if (this.beforeAvatarUpload(file)) {
        this.uploadFile = arr
      }
    },
    beforeAvatarUpload (file) {
      const isLt2M = file.size / 1024 / 1024 < 5
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 5MB!')
      }
      return isLt2M
    },
    dialogCancel () {
      this.uploadFile = []
      this.isEdit && this.$refs.upload.clearFiles()
      this.dialogFormVisible = false
    },
    dialogConfim () {
      if (!this.uploadFile[0]) {
        this.dialogCancel()
        return
      }
      this.loading = true
      const { id, imageName, parentId } = this.productDetail
      this.uploadFile.forEach(item => {
        const formData = new FormData()
        formData.append('files', item.raw)
        formData.append('id', id)
        formData.append('imageName', imageName)
        formData.append('parentId', parentId)
        updateProductDetail(formData).then(res => {
          this.$message({
            type: 'success',
            message: '编辑成功'
          })
        })
      })
      this.loading = false
      this.dialogCancel()
    },
    formatter (row) {
      return this.optionsObj[row.parentId]
    },
    // 点击查询
    searchQuery () {
      this.pageObj.pageIndex = 1
      this.getDataList()
    },
    // 分页器翻页
    handleSizeChange (val) {
      this.pageObj.pageSize = val
      this.pageObj.pageIndex = 1
      this.getDataList()
    },
    // 分页器改变每页数量
    handleCurrentChange (val) {
      this.pageObj.pageIndex = val
      this.getDataList()
    },
    // 获取分类列表
    getOptions () {
      getProductCategoryList().then(res => {
        const obj = {}
        res.forEach(item => {
          obj[item.id] = item.categoryName
        })
        this.optionsObj = obj
        this.options = listToTree(res, 0)
        localStorage.setItem('options', JSON.stringify(this.options))
      })
    },
    // 获取列表数据
    getDataList () {
      const params = {
        parentId: this.parentId[this.parentId.length - 1],
        ...this.pageObj
      }
      getProductList(params).then(res => {
        const { totalCount, pageData } = res
        this.tableData = pageData
        this.totalCount = totalCount
      })
    },
    // 编辑
    async editProduct (obj) {
      // this.$router.push({ path: '/operate/product/form', query: obj })
      await this.getProductDetail(obj)
      // console.log(this.productDetail, 'this.productDetail')
      this.dialogTitle = '编辑'
      this.isEdit = true
      this.dialogFormVisible = true
    },
    // 新增
    toAdd () {
      this.$router.push({ path: '/operate/product/form' })
    },
    // 查看
    showDetail (obj) {
      // console.log(obj)
      this.getProductDetail(obj).then(() => {
        this.dialogTitle = '查看'
        this.isEdit = false
        this.dialogFormVisible = true
      })
    },
    // 删除
    deleteProduct (obj) {
      this.$confirm(`确认删除商品--${obj.imageName}？`, '确认信息', {
        distinguishCancelAndClose: true,
        confirmButtonText: '确认',
        cancelButtonText: '取消'
      })
        .then(() => {
          deleteProduct(obj.id).then(res => {
            this.searchQuery()
            this.$message({
              type: 'info',
              message: '删除成功'
            })
          })
        })
    },
    // 获取商品详情
    getProductDetail (obj) {
      return new Promise((resolve, reject) => {
        getProductDetail({
          imageId: obj.id,
          pageSize: 100
        }).then(res => {
          this.productDetail = {
            ...obj,
            detail: res.pageData
          }
          resolve()
        })
      })
    }
  }
}
</script>

<style lang="less" scoped>
.productList {
  width: 100%;
  padding-left: 30px;
  .pageTop {
    padding: 10px 0;
  }
  .tableBox {
    overflow-x: auto;
    width: 100%;
    overflow: auto;
  }
  .showDetail {
    max-height: 60vh;
    overflow-y: auto;
    .imgLine {
      display: flex;
      flex-wrap: wrap;
      .imgLine {
        width: 100px;
      }
      .imgBox {
        position: relative;
        margin: 10px;
        width: 200px;
        border: 1px solid #eee;
        border-radius: 6px;
        >img {
          width: 200px;
        }
        .deleteBox {
          display: none;
          position: absolute;
          top: 0;right: 0;bottom: 0;left: 0;
          text-align: center;
          background: rgba(0, 0, 0, .5);
          .el-icon-delete {
            margin-top: 45%;
            font-size: 30px;
            color: #fff;
            cursor: pointer;
          }
        }
        &:hover .deleteBox{
          display: block;
        }
      }
    }
  }
}
</style>
